# Makefile for Math Library
CC = gcc
CFLAGS = -fPIC -Wall -Wextra -O2 -g -std=c99
LDFLAGS = -shared
TARGET = libmath.so
SOURCES = src/math_lib.c
OBJECTS = $(SOURCES:.c=.o)
INCLUDE_DIR = include
LIB_DIR = lib

# 默认目标
.PHONY: all clean install uninstall test run

all: $(TARGET)

# 创建库目录
$(LIB_DIR):
	mkdir -p $(LIB_DIR)

# 编译目标库
$(TARGET): $(OBJECTS) | $(LIB_DIR)
	$(CC) $(LDFLAGS) -o $(LIB_DIR)/$@ $^
	@echo "Library built: $(LIB_DIR)/$@"

# 编译源文件
%.o: %.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -I$(INCLUDE_DIR) -c $< -o $@

# 清理构建文件
clean:
	rm -rf $(OBJECTS) $(LIB_DIR) build/

# 安装到系统
install: $(TARGET)
	@if [ "$(EUID)" -ne 0 ]; then \
		echo "Please run as root (use sudo)"; \
		exit 1; \
	fi
	sudo cp $(LIB_DIR)/$(TARGET) /usr/local/lib/
	sudo cp $(INCLUDE_DIR)/*.h /usr/local/include/
	sudo ldconfig
	@echo "Library installed to /usr/local/lib/"

# 卸载
uninstall:
	@if [ "$(EUID)" -ne 0 ]; then \
		echo "Please run as root (use sudo)"; \
		exit 1; \
	fi
	sudo rm -f /usr/local/lib/$(TARGET)
	sudo rm -f /usr/local/include/math_lib.h
	sudo ldconfig
	@echo "Library uninstalled"

# 运行示例程序
run: $(TARGET)
	@echo "Running math library example..."
	$(CC) -o examples/main examples/main.c -I$(INCLUDE_DIR) -L$(LIB_DIR) -lmath
	@echo "Example program built. Run with:"
	@echo "export LD_LIBRARY_PATH=\$$(pwd)/lib:\$$LD_LIBRARY_PATH"
	@echo "./examples/main"

# 运行测试
test: $(TARGET)
	@echo "Building and running tests..."
	$(CC) -o tests/test_math tests/test_math.c -I$(INCLUDE_DIR) -L$(LIB_DIR) -lmath
	@echo "Tests built. Run with:"
	@echo "export LD_LIBRARY_PATH=\$$(pwd)/lib:\$$LD_LIBRARY_PATH"
	@echo "./tests/test_math"

# 显示帮助信息
help:
	@echo "Available targets:"
	@echo "  all       - Build the math library"
	@echo "  clean     - Remove build files"
	@echo "  install   - Install library to system (requires sudo)"
	@echo "  uninstall - Remove library from system (requires sudo)"
	@echo "  test      - Build and run tests"
	@echo "  run       - Build and run example program"
	@echo "  help      - Show this help message"

# 检查依赖
check-deps:
	@echo "Checking dependencies..."
	@which $(CC) > /dev/null || (echo "Error: $(CC) not found" && exit 1)
	@echo "Dependencies OK"

# 显示库信息
info: $(TARGET)
	@echo "Library information:"
	@file $(LIB_DIR)/$(TARGET)
	@echo "Symbols:"
	@nm -D $(LIB_DIR)/$(TARGET) | grep -E " [Tt] " | head -10
	@echo "Dependencies:"
	@ldd $(LIB_DIR)/$(TARGET) 